const axios = require('axios');

// API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

/**
 * 示例1: 从URL生成3D模型
 */
async function generateFromUrl() {
  try {
    const response = await axios.post(`${API_BASE_URL}/generate-from-url`, {
      image_url: 'https://example.com/your-image.jpg',
      options: {
        // 根据Tripo3D API文档添加适当的选项
        quality: 'high',
        style: 'realistic'
      }
    });
    
    console.log('从URL生成3D模型响应:', response.data);
    
    // 获取任务ID以便后续查询状态
    const taskId = response.data.data.task_id;
    console.log(`任务ID: ${taskId}`);
    
    // 可以开始轮询任务状态
    startTaskStatusPolling(taskId);
  } catch (error) {
    console.error('生成3D模型失败:', error.response?.data || error.message);
  }
}

/**
 * 示例2: 上传图片生成3D模型
 */
async function generateFromUpload() {
  try {
    const FormData = require('form-data');
    const fs = require('fs');
    
    const formData = new FormData();
    formData.append('image', fs.createReadStream('path/to/your/image.jpg'));
    formData.append('options', JSON.stringify({
      quality: 'medium',
      style: 'cartoon'
    }));
    
    const response = await axios.post(`${API_BASE_URL}/generate-from-upload`, formData, {
      headers: formData.getHeaders()
    });
    
    console.log('上传图片生成3D模型响应:', response.data);
    
    // 获取任务ID
    const taskId = response.data.data.task_id;
    console.log(`任务ID: ${taskId}`);
  } catch (error) {
    console.error('上传图片生成3D模型失败:', error.response?.data || error.message);
  }
}

/**
 * 示例3: 查询任务状态
 */
async function checkTaskStatus(taskId) {
  try {
    const response = await axios.get(`${API_BASE_URL}/task-status/${taskId}`);
    console.log('任务状态:', response.data);
    return response.data;
  } catch (error) {
    console.error('查询任务状态失败:', error.response?.data || error.message);
    return null;
  }
}

/**
 * 示例4: 下载3D模型
 */
async function downloadModel(modelId, format = 'glb') {
  try {
    const response = await axios.get(`${API_BASE_URL}/download-model/${modelId}`, {
      params: { format },
      responseType: 'arraybuffer'
    });
    
    // 保存模型文件
    const fs = require('fs');
    const outputPath = `./output/${modelId}.${format}`;
    fs.mkdirSync('./output', { recursive: true });
    fs.writeFileSync(outputPath, Buffer.from(response.data));
    
    console.log(`3D模型已保存到: ${outputPath}`);
  } catch (error) {
    console.error('下载3D模型失败:', error.response?.data || error.message);
  }
}

/**
 * 轮询任务状态直到完成
 */
async function startTaskStatusPolling(taskId) {
  const pollInterval = 5000; // 5秒轮询一次
  
  const interval = setInterval(async () => {
    const statusResponse = await checkTaskStatus(taskId);
    
    if (statusResponse && statusResponse.data) {
      const { status, model_id } = statusResponse.data;
      
      console.log(`当前任务状态: ${status}`);
      
      if (status === 'completed' && model_id) {
        console.log(`任务完成! 模型ID: ${model_id}`);
        clearInterval(interval);
        
        // 可以选择自动下载模型
        console.log('开始下载3D模型...');
        await downloadModel(model_id);
      } else if (status === 'failed') {
        console.error('任务失败!');
        clearInterval(interval);
      }
    }
  }, pollInterval);
}

/**
 * 主函数 - 运行示例
 */
async function runExample() {
  console.log('Tripo3D API 集成示例');
  
  // 取消注释以下行以运行相应的示例
  // await generateFromUrl();
  // await generateFromUpload();
  // await checkTaskStatus('your-task-id');
  // await downloadModel('your-model-id');
}

// 运行示例
runExample().catch(console.error);